Skip to main content

数据库的 CURD

创建一个接口类

package cn.asdasd.demo;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface GirlRepository extends JpaRepository<Girl,Integer> {
// 通过年龄查询
public List<Girl> findByAge(Integer age);
}

创建一个控制器类

package cn.asdasd.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class GirlController {

@Autowired
private GirlRepository girlRepository;

/**
* 查询所有女生列表
* @return
*/
@GetMapping(value = "/girls")
public List<Girl> girlList(){
return girlRepository.findAll();
}

/**
* 添加女生
* @param cupSize
* @param age
* @return
*/
@PostMapping(value = "/girls")
public Girl girlAdd(@RequestParam("cupSize") String cupSize,
@RequestParam("age") Integer age) {
Girl girl = new Girl();
girl.setCupSize(cupSize);
girl.setAge(age);
return girlRepository.save(girl);
}

/**
* 查询
* @param id
* @return
*/
@GetMapping(value = "/girls/{id}")
public Girl girlFindOne(@PathVariable("id") Integer id) {
return girlRepository.findById( id ).orElse(null);
}

/**
* 更新
* @param id
* @param cupSize
* @param age
* @return
*/
@PutMapping(value = "/girls/{id}")
public Girl girlUpdate(@PathVariable("id") Integer id,
@RequestParam("cupSize") String cupSize,
@RequestParam("age") Integer age) {
Girl girl = new Girl();
girl.setId(id);
girl.setCupSize(cupSize);
girl.setAge(age);

return girlRepository.save(girl);
}

/**
* 删除数据
* @param id
*/
@DeleteMapping(value = "/girls/{id}")
public void girlDelete(@PathVariable("id") Integer id) {
girlRepository.deleteById( id);
}

}